package lc.动态规划;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/10/20
 */
public class 剑指Offer47_礼物的最大价值 {

    public int maxValue(int[][] grid) {

        // 递推公式 f(i,j)=max[f(i,j−1),f(i−1,j)]+grid(i,j)
        int max = grid[0][0];
        int m = grid.length, n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) continue;
                if (i == 0) grid[i][j] += grid[i][j - 1]; // 为矩阵第一行元素，只可从左边到达；
                else if (j == 0) grid[i][j] += grid[i -1][j]; //为矩阵第一列元素，只可从上边到达；
                else grid[i][j] = Math.max(grid[i -1][j],grid[i][j - 1]) + grid[i][j]; // 可以从上面也可以从左边到达
            }
        }
        return grid[m-1][n - 1];
    }
}
